// Debug test for MockBriefingService cache mechanism
const path = require('path');
const fs = require('fs-extra');

// Copy MockBriefingService from integration test but add debug logging
class DebugMockBriefingService {
  constructor() {
    this.briefingsPath = path.join(process.cwd(), '.cb-document-helper', 'briefings');
  }

  async getBriefing(filePath) {
    try {
      const briefingFile = this.getBriefingFilePath(filePath);
      console.log(`🔍 Looking for briefing file: ${briefingFile}`);
      
      if (await fs.pathExists(briefingFile)) {
        console.log('✅ Briefing file exists, reading...');
        const briefingData = await fs.readJson(briefingFile);
        
        // 检查文件是否已修改
        const stat = await fs.stat(filePath);
        const cachedModified = new Date(briefingData.fileModified);
        
        console.log(`📅 File mtime: ${stat.mtime.toISOString()}`);
        console.log(`📅 Cached mtime: ${cachedModified.toISOString()}`);
        console.log(`🔍 Comparison: ${stat.mtime.getTime()} <= ${cachedModified.getTime()} = ${stat.mtime.getTime() <= cachedModified.getTime()}`);
        
        if (stat.mtime <= cachedModified) {
          console.log('✅ Cache hit - returning cached briefing');
          console.log(`📝 Cached briefing preview: ${briefingData.briefing.substring(0, 100)}...`);
          return briefingData.briefing;
        } else {
          console.log('❌ Cache miss - file was modified');
        }
      } else {
        console.log('❌ Briefing file does not exist');
      }

      // 如果简介不存在或文件已修改，重新生成
      console.log('🔄 Generating new briefing...');
      const content = await fs.readFile(filePath, 'utf-8');
      const matter = require('gray-matter');
      const parsed = matter(content);
      
      const documentInfo = {
        filePath,
        content,
        frontMatter: parsed.data,
        lastModified: (await fs.stat(filePath)).mtime,
      };

      // Mock a deterministic briefing (instead of calling Ollama)
      const briefing = this.generateMockBriefing(documentInfo);
      console.log(`📝 Generated briefing preview: ${briefing.substring(0, 100)}...`);
      
      // Save to cache
      await this.saveBriefing(documentInfo.filePath, briefing, documentInfo.lastModified);
      console.log('💾 Briefing saved to cache');
      
      return briefing;
    } catch (error) {
      console.error(`❌ Error getting briefing for ${filePath}:`, error);
      return `Error loading briefing for ${filePath}: ${error}`;
    }
  }

  generateMockBriefing(documentInfo) {
    // Generate a deterministic briefing based on content
    const title = documentInfo.frontMatter.title || 'Untitled';
    const contentLength = documentInfo.content.length;
    
    return `这是对文档"${title}"的摘要。文档路径：${documentInfo.filePath}，内容长度：${contentLength}字符。`;
  }

  async saveBriefing(filePath, briefing, fileModified) {
    await fs.ensureDir(this.briefingsPath);
    const briefingFile = this.getBriefingFilePath(filePath);
    
    const briefingData = {
      filePath,
      briefing,
      lastUpdated: new Date(),
      fileModified: fileModified, // This should be a Date object
    };

    console.log(`💾 Saving briefing data:`, {
      filePath: briefingData.filePath,
      briefingLength: briefingData.briefing.length,
      lastUpdated: briefingData.lastUpdated.toISOString(),
      fileModified: briefingData.fileModified.toISOString()
    });

    await fs.writeJson(briefingFile, briefingData, { spaces: 2 });
  }

  getBriefingFilePath(filePath) {
    const hash = this.hashString(filePath);
    return path.join(this.briefingsPath, `${hash}.json`);
  }

  hashString(str) {
    let hash = 0;
    for (let i = 0; i < str.length; i++) {
      const char = str.charCodeAt(i);
      hash = ((hash << 5) - hash) + char;
      hash = hash & hash;
    }
    return Math.abs(hash).toString(36);
  }

  async clearBriefings() {
    try {
      if (await fs.pathExists(this.briefingsPath)) {
        await fs.emptyDir(this.briefingsPath);
      }
    } catch (error) {
      console.error('Error clearing briefings:', error);
    }
  }
}

async function debugMockCacheTest() {
  console.log('🐛 Starting MockBriefingService cache debug test...\n');
  
  const briefingService = new DebugMockBriefingService();
  
  // Create test file
  const testFile = './debug-mock-cache-test.md';
  const testContent = `---
title: "Mock Cache Debug Test"
author: "Test User"
---

# Mock Cache Debug

This is a test file for debugging MockBriefingService cache mechanism.

## Content
- Testing cache functionality
- Using deterministic briefing generation
- Verifying cache hits and misses
`;

  try {
    // Clean up any existing cache first
    await briefingService.clearBriefings();
    console.log('🧹 Cleared existing cache\n');
    
    // Write test file
    await fs.writeFile(testFile, testContent);
    console.log('📄 Created test file\n');
    
    // First call
    console.log('=== FIRST CALL ===');
    const start1 = Date.now();
    const briefing1 = await briefingService.getBriefing(testFile);
    const time1 = Date.now() - start1;
    console.log(`⏱️  Time taken: ${time1}ms`);
    console.log(`📝 Result 1: ${briefing1}\n`);
    
    // Wait a moment to ensure different call time
    await new Promise(resolve => setTimeout(resolve, 100));
    
    // Second call (should use cache)
    console.log('=== SECOND CALL ===');
    const start2 = Date.now();
    const briefing2 = await briefingService.getBriefing(testFile);
    const time2 = Date.now() - start2;
    console.log(`⏱️  Time taken: ${time2}ms`);
    console.log(`📝 Result 2: ${briefing2}\n`);
    
    // Compare results
    console.log('=== COMPARISON ===');
    console.log(`Results match: ${briefing1 === briefing2}`);
    console.log(`Length 1: ${briefing1.length}, Length 2: ${briefing2.length}`);
    console.log(`Time comparison: ${time1}ms vs ${time2}ms (ratio: ${(time1/time2).toFixed(2)}x)`);
    
    if (briefing1 !== briefing2) {
      console.log('❌ Cache failed!');
      console.log('Diff:');
      console.log(`Result 1: "${briefing1}"`);
      console.log(`Result 2: "${briefing2}"`);
    } else {
      console.log('✅ Cache working correctly!');
    }
    
    // Test cache invalidation
    console.log('\n=== CACHE INVALIDATION TEST ===');
    await new Promise(resolve => setTimeout(resolve, 1000)); // Wait 1 second
    await fs.writeFile(testFile, testContent + '\n\n新增内容用于测试缓存失效。');
    console.log('📝 Modified test file');
    
    const start3 = Date.now();
    const briefing3 = await briefingService.getBriefing(testFile);
    const time3 = Date.now() - start3;
    console.log(`⏱️  Time taken: ${time3}ms`);
    console.log(`📝 Result 3: ${briefing3}`);
    console.log(`Cache invalidated: ${briefing3 !== briefing1}`);
    
    // Cleanup
    await fs.remove(testFile);
    console.log('\n🧹 Cleaned up test file');
    
  } catch (error) {
    console.error('💥 Debug test failed:', error);
    try {
      await fs.remove(testFile);
    } catch (cleanupError) {
      // Ignore cleanup errors
    }
  }
}

// Run debug test
debugMockCacheTest().catch(error => {
  console.error('💥 Debug test runner failed:', error);
  process.exit(1);
});
